<?php

namespace app\api\admin\v1\controller;

use app\api\admin\Controller;
use app\helper\Password;
use zhanshop\App;
use zhanshop\Helper;
use zhanshop\server\Request;
use zhanshop\server\Response;
use zhanshop\ShellCommand;
use zhanshop\util\Aes;

class Cloud extends Controller
{
    /**
     * @api GET pullVolume 更新代码
     * @apiGroup 云平台
     */
    public function pullVolume(Request $request, Response $response)
    {
        $token = $request->rawRequest()->cookie['token'] ?? '';
        if(App::make(Aes::class)->decrypt($token) == false){
            return false;
        }
        $getQuery = $request->get();
        $name = $getQuery['name'] ?? App::error()->setError('name参数不能为空', 403);
        App::make(Aes::class)->decrypt($request->rawRequest()->cookie["token"] ?? App::error()->setError('token参数不能为空', 403));
        $gitInfo = App::database()->model("clouds_volume")->where(["name" => $name])->findOrFail();


        $urls = parse_url($gitInfo['giturl']);
        $secretPull = $urls['scheme']."://".urlencode($gitInfo['gituser']).':'.$gitInfo['gitpwd'].'@'.$urls['host'].$urls['path'];
        $volumesPath = '/var/www/docker/volumes/'.$name.'/_data';
        if(file_exists($volumesPath) == false){
            $volumesPath = '/var/lib/docker/volumes/'.$name.'/_data';
        }
        if(count(scandir($volumesPath)) == 2){
            $gitpull = "git clone ".$secretPull.' '.$volumesPath;
            ShellCommand::call($gitpull, function ($msg) use ($request, $response){
                $response->toPush($request->fd(), $msg);
            });
        }else{
            chdir($volumesPath);
            $gitpull = "git pull ".$secretPull;
            ShellCommand::call($gitpull, function ($msg) use ($request, $response){
                $response->toPush($request->fd(), $msg);
            });
        }
        $response->toPush($request->fd(), 'close');

        return false;
    }
    /**
     * @api POST gitpush/{platform}/{auth} git推送
     * @apiGroup 云平台
     */
    public function gitpush(Request $request, Response $response)
    {
        $platform = $request->getData('platform');
        $auth = $request->getData('auth');
        if($platform){
            $param = $request->param();
            $class = '\\zhanshop\\service\\git\\'.ucfirst($platform);
            $repository = (new $class($param))->getRepository($auth, $param);
            if($repository){
                list($gitUrl, $branch) = $repository;
                var_dump($gitUrl, $branch);
            }
        }
        return $this->result();
    }
    /**
     * @api GET docker/{path} docker镜像
     * @apiGroup 云平台
     */
    public function docker(Request $request, Response $response)
    {
        $data = $request->validateRule([
            'code' => 'required'
        ])->getData();

        $code = $data['code'];
        if(strpos($code, ':') > 0){
            list($userName, $pwd) = explode(':', $code);
            $user = App::database()->model("system_user")->where(['user_name' => $userName])->find();
            if($user &&  Password::hashVerify($pwd, $userName, $user['password'])){
                $tars = glob(App::rootPath().DIRECTORY_SEPARATOR.'docker'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR. '*.tar');
                $result = [];
                $code = Helper::symmetryEncode("1");
                foreach ($tars as $v){
                    $result[] = 'http://'.$request->header("host").'/v1/cloud.docker/'.str_replace(App::rootPath().DIRECTORY_SEPARATOR.'docker'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR, '', $v).'?code='.$code;
                }
                return $this->result($result);
            }
        }

        if(Helper::symmetryDecode($code)){
            $path = $request->getData("path");
            $absolutePath = App::rootPath().DIRECTORY_SEPARATOR.'docker'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.$path;
            if(file_exists($absolutePath)){
                $response->rawResponse()->sendfile($absolutePath);
            }
        }
    }
    /**
     * @api GET appium/{token} appium代理
     * @apiGroup 云平台
     */
    public function getAppium(Request $request, Response $response)
    {
        $token = $request->getData("token");
        $requestUri = $request->server('request_uri');
        $requestUri = explode('/v1/cloud.appium', $requestUri)[1];
        var_dump($requestUri);
    }

    /**
     * @api POST appium/{token} appium代理
     * @apiGroup 云平台
     */
    public function postAppium(Request $request, Response $response)
    {
        $token = $request->getData("token");
        $requestUri = $request->server('request_uri');
        $requestUri = explode('/v1/cloud.appium', $requestUri)[1];
        var_dump($requestUri);
    }
}